package com.zmn.plat.admin.controller.product.productgroup;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto.StatusDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.InitialUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.engineer.dubbo.interfaces.star.CheckUsedEngineerProductGroupListRemoteService;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.product.productgroup.ProductGroup;
import com.zmn.plat.services.interfaces.product.productgroup.ProductGroupService;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;
import com.zmn.ums.dubbo.utils.DubboConsts;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 产品组基础修改Controller
 *
 * @author tanghongjun
 * @since 2020-08-19 11:18:36
 */
@RestController
@RequestMapping("/product/productgroup")
public class ProductGroupModifyController extends ProductGroupBaseController {
    private Logger logger = LoggerFactory.getLogger(ProductGroupListController.class);

    @Resource
    private ProductGroupService productGroupService;
    @Resource
    private ServAssCategoryService servAssCategoryService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    CheckUsedEngineerProductGroupListRemoteService engineerProductGroupListRemoteService;

    /**
     * 保存
     */
    @RequestMapping("/addEdit")
    @RequiresPermissions("/product/productgroup/addEdit.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody ProductGroup productGroup) {

        Date now = DateUtil.getNow();
        int groupId = productGroup.getGroupId();
        productGroup.setFirstLetter(InitialUtil.getFristEnName(productGroup.getName()));

        try {
            if (groupId == 0) {
                // 编码只能添加不能修改
                Integer groupCode = productGroupService.findMaxGropCode();
                productGroup.setCreater(getMcStaffRealName());
                productGroup.setCreateTime(now);
                productGroup.setUpdater(getMcStaffRealName());
                productGroup.setGroupCode(NumberUtil.isNullOrZero(groupCode) ? 1 : groupCode + 1);
                productGroup.setUpdateTime(now);
                // 排序值，默认100
                productGroup.setSort(100);
                productGroupService.insert(productGroup);
            } else {
                productGroup.setUpdater(getMcStaffRealName());
                productGroup.setUpdateTime(now);
                productGroupService.updateByKey(productGroup);
            }

            return ResponseDTO.success(true, "操作成功！");
        } catch (org.springframework.dao.DuplicateKeyException ex) {
            logger.error("同一业务类型分组名称不能重复！", productGroup.getName());
            return ResponseDTO.fail("同一业务类型分组名称不能重复！");
        } catch (Exception e) {
            logger.error("新增/修改失败, Exception{}, msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     * 描述:修改产品组状态
     *
     * @param ids
     *            产品组ID组成的字符串 eg: productId1,productId2
     * @param status
     *            修改的状态
     * @return: ResultDTO 执行结果
     * @auther: tanghongjun
     * @since: 2020年8月28日16:23:23
     */
    @RequestMapping(value = "updateStatus")
    @ResponseBody
    public ResponseDTO updateStatus(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "ids", defaultValue = "") String ids, @RequestParam(value = "status", defaultValue = "0") int status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的产品组！");
        }

        List<Integer> groupIds = StringUtil.convertStrsToList(ids);

        if (Objects.equals(GlobalConsts.NO, status)) {
            // 校验产品组是否被使用
            List<Integer> groupIdOfUsed = servAssCategoryService.listProductGroupIdOfUsed(groupIds);
            if (CollectionUtil.isNotNullOrEmpty(groupIdOfUsed)) {
                return ResponseDTO.fail("已有产品分类关联了产品组，暂不能禁用！");
            }

            // 校验产品组是否被工程师使用
            ResponseDTO<Boolean> responseDTO = engineerProductGroupListRemoteService.checkUsedEngineerProductGroupList(null, groupIds);
            if (responseDTO.isSuccess() && Objects.equals(responseDTO.getStatus(), StatusConsts.STATUS_SUCCESS) && !responseDTO.getData()) {
                return ResponseDTO.fail(responseDTO.getMessage());
            }

        }

        try {
            StatusDTO dto = new StatusDTO();
            dto.setIds(groupIds);
            dto.setStatus(status);
            dto.setUpdater(getMcStaffRealName());
            dto.setUpdateTime(new Date());
            productGroupService.updateStatusBatch(dto);
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        }

        return ResponseDTO.success(true, "操作成功！");
    }

    /**
     * 功能描述 :修改产品排序
     *
     * @param request
     * @param response
     * @param groupId
     * @param sort
     * @return com.zmn.common.dto.ResultDTO
     * @author tanbiao
     * @modifier
     * @since 2019/10/15
     */
    @RequestMapping(value = "updateSort")
    @ResponseBody
    public ResponseDTO updateSort(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer groupId, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (groupId == 0) {
            return ResponseDTO.fail("请选择要更改排序的产品组！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置产品组排序值！");
        }

        productGroupService.updateSortByKey(groupId, sort, getMcStaffRealName());
        return ResponseDTO.success(true, "操作成功！");
    }

    /**
     * 描述: 修改产品组报销金额
     *
     * @param groupId
     * @param reimbursementAmount
     * @return com.zmn.common.dto2.ResponseDTO
     * @author jiafei
     * @since 2021/9/6 17:39
     */
    @RequestMapping(value = "reimbursementAmount")
    public ResponseDTO<String> updateReimbursementAmount(@RequestParam(value = "groupId") Integer groupId,
                                                         @RequestParam(value = "reimbursementAmount") Integer reimbursementAmount) {

        if (NumberUtil.isPositiveInteger(groupId)) {
            return ResponseDTO.fail("请选择要修改报销金额的产品组！");
        }

        if (NumberUtil.isPositiveInteger(reimbursementAmount)) {
            return ResponseDTO.fail("请设置改报销金额值！");
        }

        productGroupService.updateReimbursementAmountByKey(groupId, reimbursementAmount, getMcStaffRealName());
        return ResponseDTO.success("操作成功！");
    }

    /**
     * 删除
     *
     * @param groupId
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    @RequiresPermissions("product/productgroup/delete")
    public ResponseDTO delete(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        if (NumberUtil.isNullOrZero(groupId)) {
            return ResponseDTO.fail("请选择要删除的数据！");
        }
        productGroupService.deleteByKey(groupId);
        return ResponseDTO.success(true,"删除成功！");
    }

}
